<?php
// +----------------------------------------------------------------------
// | CoreThink [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.corethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: jry <598821125@qq.com> <http://www.corethink.cn>
// +----------------------------------------------------------------------
namespace Home\Controller;
use Think\Controller;
/**
 * 用户控制器
 * @author jry <598821125@qq.com>
 */
class UserController extends HomeController{
    /**
     * 用户列表
     * @author jry <598821125@qq.com>
     */
    public function index(){
        $uid=is_login();
        if(!$uid)
        {
            $this->redirect('/Home/User/login');
        }
        $usertype = I('get.usertype');
        if($usertype){
            $map['usertype'] = $usertype;
        }
        $user_list = D('User')->page(!empty($_GET["p"])?$_GET["p"]:1, 24)
                              ->where($map)->order('id desc')->select();
        $page = new \Common\Util\Page(D('User')->where($map)->count(), 24);
        $this->assign('page', $page->show());
        $this->assign('umark','index');
        $this->assign('meta_title', '会员');
        $this->assign('user_list', $user_list);
        $this->display();
    }

    /**
     * 用户个人主页
     * @author jry <598821125@qq.com>
     */
    public function home(){
        $uid = I('get.uid');
        if(!$uid){
            $uid  = $this->is_login();
        }
        $user_info = D('User')->where($con)->find($uid);
        if($user_info['status'] !== '1'){
            $this->error('该用户不存在或已禁用');
        }
        $this->assign('meta_title', $user_info['username'].'的主页');
        $this->assign('user_info', $user_info);
        $this->display();
    }

    /**
     * 用户个人中心
     * @author jry <598821125@qq.com>
     */
    public function center(){
        $uid=is_login();
        if(!$uid)
        {
            $this->redirect('/Home/User/login');
        }
        $this->assign('meta_title', '个人中心');
        $this->display();
    }

    /**
     * 用户修改信息
     * @author jry <598821125@qq.com>
     */
    public function profile(){
        $uid=is_login();
        if(!$uid)
        {
            $this->redirect('/Home/User/login');
        }
        if(IS_POST){
            $user_object = D('User');
            $_POST['id'] = $this->is_login();
            $result = $user_object->update($_POST);
            if($result){
                $this->success('信息修改成功');
            }else{
                $this->error($user_object->getError());
            }
        }else{
            $user_object = D('User');
            $user_info = $user_object->find($this->is_login());

            //使用FormBuilder快速建立表单页面。
            $builder = new \Common\Builder\FormBuilder();
            $builder->setMetaTitle('修改'.$user_info['username'].'的信息')  //设置页面标题
                    ->setPostUrl(U('')) //设置表单提交地址
                    ->addFormItem('username', 'text', '用户名', '')
                    ->addFormItem('avatar', 'picture', '头像', '')
                    ->addFormItem('sex', 'radio', '性别', '', $user_object->user_sex())
                    ->addFormItem('age', 'num', '年龄', '')
                    ->addFormItem('birthday', 'date', '生日', '生日')
                    ->addFormItem('summary', 'text', '签名', '一句话介绍')
                    ->setFormData($user_info)
                    ->setTemplate('_Builder/formbuilder_user')
                    ->display();
        }
    }

    /**
     * 登陆
     * @author jry <598821125@qq.com>
     */
    public function login(){
        
        if(IS_POST){
            $username = I('username');
            $password = I('password');
            if(!$username){
                $this->error('请输入账号！');
            }
            if(!$password){
                $this->error('请输入密码！');
            }
            $user_object = D('User');
            $uid = $user_object->login($username, $password);
            if(0 < $uid){
                $this->success('登录成功！', U('Home/Index/index'));//Cookie('__forward__') ? : C('HOME_PAGE')
            }else{
                $this->error($user_object->getError());
            }
        }else{
            if(is_login()){
                $this->error("您已登陆系统", U('Home/Index/index'));//Cookie('__forward__') ? : C('HOME_PAGE')
            }
            
            $this->meta_title = '用户登录';
            $this->display();
        }
    }

    /**
     * 注销
     * @author jry <598821125@qq.com>
     */
    public function logout(){
        session('user_auth', null);
        session('user_auth_sign', null);
        redirect(U('Home/Index/index'));//Cookie('__forward__') ? : C('HOME_PAGE')
    }

    /**
     * 用户注册
     * @author jry <598821125@qq.com>
     */
    public function register(){
        if(IS_POST){
        	if(!C('TOGGLE_USER_REGISTER')){
        		$this->error('注册已关闭！');
        	}
        	$_POST['reg_type']=1;
        	$username = I('post.username');
        	$password = I('post.password');
        	$two_password=I('post.two_password');
        	
        	$user_object = D('User');
        	$data = $user_object->create($_POST);
        	if($data){
        		$id = $user_object->add();
        		if($id){
        			session('reg_verify', null);
        			$uid = $user_object->login($username, $password);
        			$this->success('注册成功', U('Index/index'));
        		}else{
        			$this->error('注册失败');
        		}
        	}else{
        		$this->error($user_object->getError());
        	}
        }else{
            if(is_login()){
                $this->error("您已登陆系统", Cookie('__forward__') ? : C('HOME_PAGE'));
            }
            $this->assign('umark','register');
            $this->meta_title = '用户注册';
            $this->display();
        }
    }
	function loginUser()
	{
		$username = I('username');
		$password = I('password');
		if(!$username){
			$return['msg']='请输入账号！';
			$return['status']=false;
			$this->ajaxReturn($return);
		}
		if(!$password){
			$return['msg']='请输入密码！';
			$return['status']=false;
			$this->ajaxReturn($return);
		}
		$user_object = D('User');
		$uid = $user_object->login($username, $password);
		if(0 < $uid){
			$return['msg']='登录成功！';
			$return['url']=U('Home/Index/index');//Cookie('__forward__') ? : C('HOME_PAGE');
			$return['status']=true;
			$this->ajaxReturn($return);
		}else{
			$return['msg']=$user_object->getError();
			$return['status']=false;
			$this->ajaxReturn($return);
		}
	}
	function reg_user()
	{
	    
		$data['reg_type']=1;
		$data['username'] = I('username');
		if(!$data['username']){
			$return['msg']='请输入账号！';
			$return['status']=false;
			$this->ajaxReturn($return);
		}
		$xs=M('User')->where(array('username'=>$data['username']))->find();
		
		if($xs)
		{
			$return['msg']='此登录账户存在，请更换登录账户';
			$return['status']=false;
			$this->ajaxReturn($return);
		}
		if(strlen($data['username']) <3 )
		{
			$return['msg']='编号不能少于3个字符';
			$return['status']=false;
			$this->ajaxReturn($return);
		}
		 
		$reg1='/^[0-9a-zA-Z]+$/';
		if(!preg_match($reg1,$data['username']))
		{
			$return['msg']='会员编号只能是字母数字';
			$return['status']=false;
			$this->ajaxReturn($return);
		}
		$data['realname']=I('realname');
		$data['mobile']=I('mobile');
		if(!$data['mobile']){
			$return['msg']='请输入手机号！';
			$return['status']=false;
			$this->ajaxReturn($return);
		}
		$data['password'] = I('password');
		if(!$data['password']){
			$return['msg']='请输入登录密码！';
			$return['status']=false;
			$this->ajaxReturn($return);
		}
		$tuijian_number=I('referee');
        	if(empty($tuijian_number)){
        		$return['msg']='请输入推荐人编号！';
				$return['status']=false;
				$this->ajaxReturn($return);
        	}
        	$tuijianinfo=M('User')->where(array('username'=>$tuijian_number,'status'=>1))->find();
        	if(empty($tuijianinfo)){
        		$return['msg']='推荐人不存在！';
				$return['status']=false;
				$this->ajaxReturn($return);
        	}
        	$data['refereeid']=$tuijianinfo['id'];
			$data['two_password']=I('two_password');
		if(!$data['two_password']){
			$return['msg']='请输入交易密码！';
			$return['status']=false;
			$this->ajaxReturn($return);
		}
// 		file_put_contents('data.txt', json_encode($data));
		$user_object = D('User');
	
		$data['express_password']=$data['password'].','.$data['two_password'];//记录明文密码
		$data['password']=user_md5($data['password']);
		$data['two_password']=user_md5($data['two_password']);
		$data = $user_object->create($data);
		if($data){
			$id = $user_object->add();
			if($id){
				D('Common/UserReferee') -> adduser($id,$data['refereeid']);
				$return['msg']='注册成功,请登录！';
				$return['url']=U('User/login');
				$return['status']=true;
				$this->ajaxReturn($return);
			}else{
				$return['msg']='注册失败';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
		}else{
			$return['msg']=$user_object->getError();
			$return['status']=false;
			$this->ajaxReturn($return);
		}
	}
	function checkUser()
	{
		$referee=I('referee');
		$info=M("User")->where(array('username'=>$referee,'status'=>1))->find();
		if($info)
		{
			$data['name']='姓名：'.$info['realname'];
		}else{
			$data['name']='会员不存在或禁用';
		}
		$this->ajaxReturn($data);
	}
  public function info(){
        $uid=is_login();
        if(!$uid)
        {
            $this->redirect('/Home/User/login');
        }
      $info=M('User')->where(array('id'=>$uid,'status'=>1))->find();
      if(!$info){
          $this->error('会员不存在或被禁用！');
          exit;
     }
     $this->assign('title1','账户中心');
     $this->assign("title2",'账户信息');
     $this->assign('umark','info');
     $this->assign('info',$info);
     $this->display();
  }
  public function updateuinfo(){
      $uid=is_login();
      if(!$uid)
      {
          $this->redirect('/Home/User/login');
      }      
      $udata['username']=I('post.username');
      $udata['realname']=I('post.realname');
      $udata['area']=I('post.area');
      $udata['email']=I('post.email');
      $udata['mobile']=I('post.mobile');      
      $config=C('UPLOAD_CONFIG');
      // 上传文件
//       $upload = new \Think\Upload($config);// 实例化上传类   avatar
//       $info = $upload->uploadOne();
//       if(!$info) {// 上传错误提示错误信息
//           $this->error($upload->getError()
//               );
//       }else{// 上传成功 获取上传文件信息
//           $da['path']="/Uploads/".$info['savepath'].$info['savename'];
//           $da['name']=$info['name'];
//           $da['size']=$info['size'];
//           $da['ext']=$info['ext'];
//           $da['md5']=$info['md5'];
//           $da['sha1']=$info['sha1'];
//           $da['ctime']=time();
//           $da['status']=1;
//           $re=M('Upload')->add($da);             
//           $udata['avatar']=$re;         
//       }
      $res=M('User')->where(array('id'=>$uid))->save($udata);
      if($res){
          $this->success('修改成功！');
      }else{
          $this->error('修改失败！');
      }
      //$this->assign('info',$info);
      $this->assign('umark','updateuinfo');
      $this->display();
  }
    /**
     * 密码重置
     * @author jry <598821125@qq.com>
     */
    public function resetPassword(){
        if(IS_POST){
            $reg_type = I('post.reg_type');
            switch($reg_type){
                case 'email':
                    $username = I('post.email');
                    $condition['email'] = I('post.email');
                    break;
                case 'mobile':
                    $username = I('post.mobile');
                    $condition['mobile'] = I('post.mobile');
                    break;
            }
            //验证码严格加盐加密验证
            if(user_md5(I('post.verify'), $username) !== session('reg_verify')){
                $this->error('验证码错误！');
            }
            $user_object = D('User');
            $data = $user_object->create($_POST, 5); //调用自动验证
            if(!$data){
                $this->error($user_object->getError());
            }
            $result = $user_object->where($condition)->setField('password', $data['password']); //重置密码
            $uid = $user_object->login($username, I('post.password')); //自动登录
            if($uid){
                $this->success('密码重置成功', C('HOME_PAGE'));
            }else{
                $this->error('密码重置失败');
            }
        }else{
            $this->meta_title = '密码重置';
            $this->assign('umark','resetPassword');
            $this->display();
        }
    }

    /**
     * 图片验证码生成，用于登录和注册
     * @author jry <598821125@qq.com>
     */
    public function verify($vid = 1){
        $verify = new \Think\Verify();
        $verify->length = 4;
        $verify->entry($vid);
    }
    
    /**
     * 检测验证码
     * @param  integer $id 验证码ID
     * @return boolean 检测结果
     */
    function check_verify($code, $vid = 1){
        $verify = new \Think\Verify();
        return $verify->check($code, $vid);
    }

    /**
     * 邮箱验证码，用于注册
     * @author jry <598821125@qq.com>
     */
    public function sendMailVerify(){
        $user_object = D('User');
        $result = $user_object->create($_POST, 5); //调用自动验证
        if(!$result){
            $this->error($user_object->getError());
        }

        //生成验证码
        $reg_verify = \Org\Util\String::randString(6,1);
        session('reg_verify', user_md5($reg_verify, I('post.email')));

        //构造邮件数据
        $mail_data['receiver'] = I('post.email');
        $mail_data['subject']  = '邮箱验证';
        $mail_data['content'] = '少侠/女侠好：<br>听闻您正使用该邮箱'.I('post.email').'【注册/修改密码】，请在验证码输入框中输入：
        <span style="color:red;font-weight:bold;">'.$reg_verify.'</span>，以完成操作。<br>
        注意：此操作可能会修改您的密码、登录邮箱或绑定手机。如非本人操作，请及时登录并修改
        密码以保证帐户安全 （工作人员不会向您索取此验证码，请勿泄漏！)';

        //发送邮件
        if(send_mail($mail_data)){
            $this->success('发送成功，请登陆邮箱查收！');
        }else{
            $this->error('发送失败！');
        }
    }

    /**
     * 短信验证码，用于注册
     * @author jry <598821125@qq.com>
     */
    public function sendMobileVerify(){
        $user_object = D('User');
        $result = $user_object->create($_POST, 5); //调用自动验证
        if(!$result){
            $this->error($user_object->getError());
        }

        //生成验证码
        $reg_verify = \Org\Util\String::randString(6,1);
        session('reg_verify', user_md5($reg_verify, I('post.mobile')));

        //构造短信数据
        $msg_data['receiver'] = I('post.mobile');
        $msg_data['message'] = '短信验证码：'.$reg_verify;
        if(send_mobile_message($msg_data)){
            $this->success('发送成功，请查收！');
        }else{
            $this->error('发送失败！');
        }
    }
    /*
     * 推荐人列表
     * */
    
    public function reglist(){
        $uid=is_login();
        if(!$uid)
        {
            $this->redirect('/Home/User/login');
        }
        $list=M('User')->where(array('refereeid'=>$uid))->select();
        $this->assign('title1','账户中心');
        $this->assign("title2",'币交所会员');
        $this->assign('umark','reglist');
        $this->assign('list',$list);
        $this->display();
    }
    
    /*
     * 推荐人列表
     * */
    public function pwd(){
        $uid=is_login();
        if(!$uid)
        {
            $this->redirect('/Home/User/login');
        }
        $this->assign('title1','账户中心');
        $this->assign("title2",'修改密码');
        $this->assign('umark','pwd');
        $this->display();
    }
    public function updatepwd(){
        $uid=is_login();
        if(!$uid)
        {
            $this->redirect('/Home/User/login');
        }  
        $info=M('User')->where(array('id'=>$uid))->find();
        $psd_type=I('psd_type');
        $old = I("old");
        $repassword = I("repassword");
        $password = I("password");
        $expwd=$info['express_password'];
        $arr=explode(',', $expwd);
       if($psd_type == 1){
           $oldpwd=user_md5($old);
           if(user_md5($old) !=$info['password']){
               $return['msg']='原登录密码不正确';
           }else{
               $data['express_password']=$password.','.$arr[1];
               $data['password']=user_md5($password);
               $res=D('User')->where(array('id'=>$uid))->save($data);
               if($res){
                   $return['msg']='修改成功';
               }else{
                   $return['msg']='修改失败';
               }
           }
       }elseif($psd_type == 2){
           $oldpwd=user_md5($old);
           if(user_md5($old) !=$info['two_password']){
               $return['msg']='原交易密码不正确';
           }else{
               $data['express_password']=$arr[0].','.$password;
               $data['two_password']=user_md5($password);
               $res=D('User')->where(array('id'=>$uid))->save($data);
               if($res){
                   $return['msg']='修改成功';
               }else{
                   $return['msg']='修改失败';
               }
           }
       }
        $this->ajaxReturn($return);
    }
    /*
     * 邀请好友
     * */
    public function invite(){
        $uid=is_login();
        if(!$uid)
        {
            $this->redirect('/Home/User/login');
        }
        
        $invite_list=M('User')->where(array('refereeid'=>$uid))->select();//邀请人列表
        $umane=M('User')->where(array('id'=>$uid))->find();
        $this->assign('title1','账户中心');
        $this->assign("title2",'邀请好友');
        $this->assign('list',$invite_list);
        $this->assign('uname',$umane['username']);
        $this->assign('umark','invite');
        $this->display();
    }
   
}
